<template>
  <div class="registerDetail">
    <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow :fixed="true" :placeholder="true" @click-left="$router.go(-1)" />
    <!-- 表单 -->
    <div class="formData">
      <van-form ref="form" @submit="formOnSubmit">
        <van-field required v-model="formData.showOrgName" name="所属展厅" label="所属展厅" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelect('showOrgId', 'showOrgName')" readonly :rules="[{ required: true }]" />
        <van-field required v-model="formData.webTypeName" name="线索来源" label="线索来源" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelect('webType', 'webTypeName')" readonly :rules="[{ required: true }]" />
        <van-field required v-model="formData.leadsTypeName" name="线索类型" label="线索类型" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelect('leadsType', 'leadsTypeName')" readonly :rules="[{ required: true }]" />
        <van-field required v-model="formData.customerName" name="客户名称" label="客户名称" input-align="right" placeholder="请输入" :rules="[{ required: true }]" />
        <van-field required v-model="formData.phone" name="客户联系方式" label="客户联系方式" input-align="right" placeholder="请输入" :rules="[{ required: true }]" />
        <van-field required name="radio" label="客户性别" input-align="right" :rules="[{ required: true }]">
          <template #input>
            <van-radio-group v-model="formData.customerSex" direction="horizontal">
              <van-radio :name="item.value" v-for="(item, index) in customerSexList" :key="index">{{ item.name }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field required v-model="formData.brandName" name="意向品牌" label="意向品牌" input-align="right" placeholder="请输入" :rules="[{ required: true }]" />

        <van-field required v-model="formData.serialName" name="意向车系" label="意向车系" input-align="right" placeholder="请输入" :rules="[{ required: true }]" />

        <van-field required v-model="formData.carModelName" name="意向车型" label="意向车型" input-align="right" placeholder="请输入" :rules="[{ required: true }]" />

        <van-field v-model="formData.carStockName" name="关联意向车辆" label="关联意向车辆" input-align="right" placeholder="请选择" right-icon="arrow" readonly @click="handleMoreSelect('carStockId', 'carStockName')" />

        <van-field required v-model="formData.province" name="省份" label="省份" input-align="right" placeholder="请输入" :rules="[{ required: true }]" />

        <van-field required v-model="formData.city" name="城市" label="城市" input-align="right" placeholder="请输入" :rules="[{ required: true }]" />

        <van-field required v-model="formData.location" name="区域" label="区域" input-align="right" placeholder="请输入" :rules="[{ required: true }]" />

        <van-field v-model="formData.note" name="备注" label="备注" type="textarea" input-align="left" placeholder />

        <!-- 下拉选择弹窗 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-picker show-toolbar :columns="columns" @confirm="handleSelectConfirm" @cancel="showSelectPicker = false" value-key="name" />
        </van-popup>
        <div class="footerBtn">
          <div class="submitBtn" @click="formOnSubmit">提交</div>
        </div>
      </van-form>
    </div>
    <van-popup v-model="showSelectCarStockId">
      <inventory-manage :showOrgId="formData.showOrgId" @getcarStock="getcarStock" @cancel="showSelectCarStockId = false" @clearlSelect="
          formData.carStockId = ''
          formData.carStockName = ''
          showSelectCarStockId = false
        "></inventory-manage>
    </van-popup>
  </div>
</template>

<script>
import {
  Search,
  Empty,
  Field,
  Form,
  Uploader,
  DatetimePicker,
  Tab,
  Tabs,
  ImagePreview
} from "vant";
import taskApi from "@/api/taskApi";
import sellManageApi from "@/api/sellManageApi";
import { getCookies } from "@/utils/util.js";
import commonApi from "@/api/commonApi";
import inventoryManage from "./inventoryManage";
// import { delete } from 'vue/types/umd';
export default {
  name: "taskCenterEdit",
  components: {
    Search,
    Empty,
    Field,
    Form,
    Uploader,
    DatetimePicker,
    Tab,
    Tabs,
    ImagePreview,
    inventoryManage
  },
  data() {
    return {
      showTimerPicker: false,
      showOrgList: "",
      leadsSourceList: "",
      webTypeList: "",
      dataSource: {
        method: "addSalesLeads", //固定值
        showOrgId: "", //展厅ID，必填
        showOrgName: "", // 展厅名称
        webType: "", //线索来源，String，必填
        leadsType: "", //线索类型，String，必填
        customerName: "", //客户名称,必填，String
        phone: "", //客户联系方式,必填，String
        customerSex: "", //客户性别,必填，String
        brandName: "", //意向品牌,必填，String
        serialName: "", //意向车系,必填，String
        carModelName: "", //意向车型,必填，String
        carStockId: "", //关联意向车辆库存表ID，String
        province: "", //省份,必填，String
        city: "", //城市,必填，String
        location: "", //区域,必填，String
        note: "", //备注，String
        orgId: "", //组织ID,必填
        userId: "" //用户ID，必填，String
      },
      formData: {
        method: "addSalesLeads", //固定值
        showOrgId: "", //展厅ID，必填
        showOrgName: "", // 展厅名称
        webType: "", //线索来源，String，必填
        leadsType: "", //线索类型，String，必填
        customerName: "", //客户名称,必填，String
        phone: "", //客户联系方式,必填，String
        customerSex: "", //客户性别,必填，String
        brandName: "", //意向品牌,必填，String
        serialName: "", //意向车系,必填，String
        carModelName: "", //意向车型,必填，String
        carStockId: "", //关联意向车辆库存表ID，String
        province: "", //省份,必填，String
        city: "", //城市,必填，String
        location: "", //区域,必填，String
        note: "", //备注，String
        orgId: "", //组织ID,必填
        userId: "" //用户ID，必填，String
      },
      columns: [],
      showSelectPicker: false,
      detailId: "",
      userId: getCookies("userId"), //用户ID，必填，String
      isflagList: [
        { name: "是", value: 1 },
        { name: "否", value: 0 }
      ],
      customerSexList: [
        { name: "男", value: 1 },
        { name: "女", value: 0 }
      ],
      showSelectCarStockId: false
    };
  },

  mounted() {
    if (this.$route.query) {
      // this.detailId = this.$route.query.billId;
      this.userId = getCookies("userId");
      // this.getDetail(this.detailId);
      this.getShowOrgByUser();
      this.getLeadsSource();
      this.getStateName();
    }
  },
  methods: {
    // 获取关联意向车辆信息
    getcarStock(data) {
      this.formData.carStockId = data.carStockId;
      this.formData.carStockName = data.carStockName;
      this.showSelectCarStockId = false;
    },
    // 关联意向车辆
    handleMoreSelect() {
      if (this.formData.showOrgId) {
        this.showSelectCarStockId = true;
      } else {
        this.$toast.fail("请先选择展厅");
      }
    },
    // 获取线索来源 词典
    getStateName() {
      sellManageApi
        .getEnums({ key: "salesWebTypeEnum", userId: getCookies("userId") })
        .then(res => {
          if (res.data) {
            this.webTypeList = res.data;
          }
        });
    },
    // 根据用户获取对应展厅
    getShowOrgByUser() {
      let userId = getCookies("userId");
      sellManageApi
        .secondHandCarFacade({
          method: "getShowOrgByUser", //固定值
          orgKey: "showOrg", // orgkey
          userId: userId //用户ID，必填，String
        })
        .then(res => {
          if (res.data) {
            this.showOrgList = res.data;
          }
        });
    },
    // 获取维修中心
    getMainFixCenter() {
      commonApi
        .getMainFixCenter({
          orgId: "test",
          userId: this.userId,
          type: "fixCenter"
        })
        .then(res => {
          if (res.data) {
            this.showOrgList = res.data;
          }
        });
    },
    // 获取线索类型
    getLeadsSource() {
      commonApi
        .getEnums({
          key: "salesLeadsType",
          userId: this.userId
        })
        .then(res => {
          if (res.data) {
            this.leadsSourceList = res.data;
          }
        });
    },
    // 获取销售线索详情
    getDetail(billId) {
      let userId = getCookies("userId");
      sellManageApi
        .secondHandCarFacade({
          method: "getSalesLeadsById", //固定值
          billId: billId,
          userId: userId //用户ID，必填，String
        })
        .then(res => {
          this.dataSource = res.data;
          this.formData = res.data;
        });
    },

    // 选择下拉
    handleSelect(field, fieldName) {
      this.showSelectPicker = true;
      if (field == "repair") {
        this.columns = [
          { name: "是", value: 1 },
          { name: "否", value: 2 }
        ];
      } else if (field == "outUser") {
        this.columns = [
          { name: "服务人员1", value: 1 },
          { name: "服务人员2", value: 2 }
        ];
      } else if (field == "showOrgId") {
        this.columns = this.showOrgList;
      } else if (field == "leadsType") {
        this.columns = this.leadsSourceList;
      } else if (field == "webType") {
        this.columns = this.webTypeList;
      }
      this.field = field;
      this.fieldName = fieldName;
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.formData[this.field] = value.billId ? value.billId : value.value;
      this.formData[this.fieldName] = value.name;
      console.log(this.formData);
      this.showSelectPicker = false;
    },

    onConfirm(val, field) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.formData[field] = `${year}-${month}-${day} ${hour}:${minute}:00`;
      this.showTimerPicker = false;
    },

    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      } else if (type === "second") {
        return `${value}秒`;
      }
      return value;
    },
    // 时间选择
    handleSelectTime(field) {
      this.timeField = field;
      this.showTimerPicker = true;
    },
    onTimeConfirm(val) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.formData[
        this.timeField
      ] = `${year}-${month}-${day} ${hour}:${minute}:00`;
      this.showTimerPicker = false;
    },
    //维修预约
    applyRepair() {
      this.$router.push("/applyRepair");
    },
    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter(item => {
          return item[key] == val;
        });
        if (obj.length > 0) {
          return obj[0].name;
        }
      }
      return null;
    },
    formOnSubmit() {
      this.$refs.form
        .validate()
        .then(res => {
          let formData = JSON.parse(JSON.stringify(this.formData));
          delete formData.showOrgName;
          delete formData.webTypeName;
          delete formData.leadsTypeName;
          sellManageApi
            .secondHandCarFacade({
              ...formData
            })
            .then(res => {
              console.log(res);
              if (res.code == 1) {
                this.$toast.success("提交成功");
                this.$router.go(-1);
              }
            });
          this.loading = true;
        })
        .catch(() => {
          this.loading = false;
          this.$toast.fail("请完善信息");
        });
    }
  }
};
</script>

<style lang="less" scoped>
body {
  background: #f3f3f3;
}
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  overflow: hidden;
  .detail_header {
    justify-content: space-between;
    margin: 10px 10px;
    border-radius: 5px;
    background: #fff;
    padding: 15px;
    .detail_header_lt {
      .carNo {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 10px;
        .carStatus {
          border: 1px solid #35bc04;
          color: #35bc04;
          border-radius: 5px;
          padding: 5px 5px;
          font-size: 12px;
          text-align: center;
          margin-left: 5px;
        }
      }
      .hank {
        font-size: 14px;
        color: #666;
        .name {
          border-right: 2px solid #ccc;
          padding-right: 5px;
          margin-right: 5px;
        }
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 14px;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 16px;
        padding: 5px;
        border-radius: 50%;
        margin-right: 5px;
      }
    }
  }
  .formData {
    background: #fff;
    overflow: hidden;
  }
}

.footerBtn {
  display: flex;
  justify-content: space-between;
  width: 80%;
  margin: auto;
  padding-bottom: 50px;
  background: #fff;
  margin-top: 25px;
  .saveBtn {
    background: #ccc;
    color: #fff;
    width: 45%;
    margin: auto;
    text-align: center;
    padding: 12px;
    border-radius: 5px;
    font-size: 15px;
    margin-right: 10px;
  }
  .submitBtn {
    background: #409eff;
    color: #fff;
    width: 45%;
    margin: auto;
    text-align: center;
    padding: 12px;
    border-radius: 5px;
    font-size: 15px;
  }
}
</style>
